/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.risk.control.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.common.core.util.QRCodeUtils;
import com.hopes.bizz.risk.control.dto.RiskUnitDTO;
import com.hopes.bizz.risk.control.dto.RiskUnitExcelDTO;
import com.hopes.bizz.risk.control.entity.RiskUnitEntity;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.bizz.risk.control.vo.RiskUnitExcelVO;
import com.hopes.bizz.risk.control.vo.RiskUnitVO;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.common.core.exception.BizException;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 风险分析单元
 *
 * @author daijie
 * @date 2023-07-17 18:53:13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/riskUnit" )
@Tag(description = "RiskUnit" , name = "风险分析单元管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class RiskUnitController {

    private final RiskUnitService riskUnitService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param riskUnit 风险分析单元
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('control_risk_unit_view')" )
    public R getRiskUnitPage(Page page, RiskUnitEntity riskUnit) {
        return R.ok(riskUnitService.listPage(page, riskUnit));
    }

    /**
     * 通过id查询风险分析单元
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('control_risk_unit_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        RiskUnitEntity entity = riskUnitService.getById(id);
        RiskUnitVO vo = new RiskUnitVO();
        BeanUtils.copyProperties(entity, vo);
        return R.ok(vo);
    }

    @Operation(summary = "查看风险分析单元二维码" , description = "查看风险分析单元二维码" )
    @GetMapping(value = "qrInfo/{id}")
    @PreAuthorize("@pms.hasPermission('control_risk_unit_view')" )
    public void info(@PathVariable("id" ) Long id, HttpServletResponse response) {
        try {
            RiskUnitEntity entity = riskUnitService.getById(id);
            ServletOutputStream out = response.getOutputStream();
            if (StringUtil.isNotBlank(entity.getQrCode())) {
                QRCodeUtils.encode(entity.getQrCode(), out);
            } else {
                QRCodeUtils.encode(String.valueOf(entity.getId()), out);
            }
        } catch (Exception ex) {
            log.error("查看风险分析单元二维码", ex);
        }
    }

    /**
     * 新增风险分析单元
     * @param dto 风险分析单元dto
     * @return R
     */
    @Operation(summary = "新增风险分析单元" , description = "新增风险分析单元" )
    @SysLog("新增风险分析单元" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('control_risk_unit_add')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R save(@RequestBody RiskUnitDTO dto) {
        return R.ok(riskUnitService.save(dto.toPO()));
    }

    /**
     * 修改风险分析单元
     * @param dto 风险分析单元dto
     * @return R
     */
    @Operation(summary = "修改风险分析单元" , description = "修改风险分析单元" )
    @SysLog("修改风险分析单元" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('control_risk_unit_edit')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R updateById(@RequestBody RiskUnitDTO dto) {
        return R.ok(riskUnitService.updateById(dto.toPO()));
    }

    /**
     * 通过id删除风险分析单元
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除风险分析单元" , description = "通过id删除风险分析单元" )
    @SysLog("通过id删除风险分析单元" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('control_risk_unit_del')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R removeById(@RequestBody Long[] ids) {
        return riskUnitService.removeBatchByIds(ids);
    }

    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('control_risk_unit_export')")
    public List<RiskUnitExcelVO> template() {
        return riskUnitService.exportExcel(Arrays.asList(new RiskUnitEntity()));
    }

    /**
     * 导出excel 表格
     * @param riskUnit 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('control_risk_unit_export')")
    public List<RiskUnitExcelVO> export(RiskUnitEntity riskUnit) {
        LambdaQueryWrapper<RiskUnitEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(riskUnit.getRiskObjectId()), RiskUnitEntity::getRiskObjectId, riskUnit.getRiskObjectId());
        wrapper.like(StringUtil.isNotBlank(riskUnit.getDeptId()), RiskUnitEntity::getDeptId, riskUnit.getDeptId());
        wrapper.eq(ObjectUtil.isNotNull(riskUnit.getRiskUnitType()), RiskUnitEntity::getRiskUnitType, riskUnit.getRiskUnitType());
        wrapper.eq(ObjectUtil.isNotNull(riskUnit.getRiskLevel()), RiskUnitEntity::getRiskLevel, riskUnit.getRiskLevel());
        wrapper.eq(StringUtil.isNotBlank(riskUnit.getControlLevel()), RiskUnitEntity::getControlLevel, riskUnit.getControlLevel());
        wrapper.like(ObjectUtil.isNotNull(riskUnit.getRiskName()), RiskUnitEntity::getRiskName, riskUnit.getRiskName());
        wrapper.eq(ObjectUtil.isNotNull(riskUnit.getIdentifyFlag()), RiskUnitEntity::getIdentifyFlag, riskUnit.getIdentifyFlag());

        return riskUnitService.exportExcel(riskUnitService.list(wrapper));
    }

    /**
     * 导入excel 表格
     * @param riskUnitExcelDtoList 查询条件
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('control_risk_unit_export')")
    public R importExcel(@RequestExcel List<RiskUnitExcelDTO> riskUnitExcelDtoList, BindingResult bindingResult) {
        if (riskUnitExcelDtoList.size() == 1 && riskUnitExcelDtoList.get(0).getRiskName() == null) {
            throw new BizException("内容为空，不可导入");
        }
        return riskUnitService.importExcel(riskUnitExcelDtoList, bindingResult);
    }
}
